package com.jingdianjichi.handler;

import com.jingdianjichi.util.RedisUtil;
import com.jingdianjichi.util.WxUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 验证码消息处理器
 */
@Component
@Slf4j
public class PostCaptchaHandler implements CallBackTypeHandler {


    @Resource
    private RedisUtil redisUtil;

    private static final String LOGIN_PREFIX = "loginCode";
    
    private static final SecureRandom RANDOM = new SecureRandom();
    
    @Override
    public String handle(Map<String, String> messageMap) {
        String fromUserName = messageMap.get("FromUserName");
        String toUserName = messageMap.get("ToUserName");
        String content = messageMap.get("Content");
        
        // 检查是否是验证码请求
        if ("验证码".equals(content)) {
            // 生成3位随机数字验证码
            int captcha = 100 + RANDOM.nextInt(900); // 100-999之间的随机数
            
            // 构建回复消息
            Map<String, String> replyMap = new HashMap<>();
            replyMap.put("ToUserName", fromUserName); // 回复给发送者
            replyMap.put("FromUserName", toUserName); // 来自公众号
            replyMap.put("CreateTime", String.valueOf(System.currentTimeMillis() / 1000));
            replyMap.put("MsgType", "text");
            replyMap.put("Content", "您的验证码是：" + captcha);
            String key = redisUtil.buildKey(LOGIN_PREFIX, String.valueOf(captcha));
            redisUtil.setNx(key, fromUserName, 5L, TimeUnit.MINUTES);
            // 发送验证码到用户
            log.info("发送验证码到用户{}：{}", fromUserName, captcha);
            return WxUtil.buildWeChatXml(replyMap);
        }
        
        // 如果不是验证码请求，返回空字符串（不回复）
        return "你好，这里是码域通，很高心认识您，您可以发送“验证码”获取登录验证码";
    }
}
